#!/user/bin/env python
# -*- coding: utf-8 -*-
''' 
Author: Sjy
Description: 优化结果展示
'''

__all__= []
import json
import numpy as np
import copy
import csv
from PyQt5 import QtCore, QtWidgets, QtGui

import gui.controls.envs as envs
from ..actions import Actions


global SHOW_DLG
SHOW_DLG = None

class DlgShowOptimizationCurve(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        global SHOW_DLG
        py3d = envs.GL.get_value('py3d')
        super().__init__(py3d)
        if SHOW_DLG!=None: return
        SHOW_DLG = self
        self.ui = _UI()
        self.ui.setupUi(self)
        # 重新启用信号
        self.finished.connect(self.closeDialog)
        self.resize(1200, 800)

    def init(self):
        data =  {}
        self.ui._init(copy.deepcopy(data))
    def on_save(self, data:dict={}):
        self.close()
        # 注意添加完了 需要更新tree 中对应位置的数据节点 用于显示

    def closeDialog(self):
        global SHOW_DLG
        SHOW_DLG = None
        self.deleteLater()

class _UI(QtWidgets.QWidget):
    sigOnSave = QtCore.pyqtSignal(dict)
    def __init__(self):
        super().__init__()
        self.parent = None
        self.__data = {}
    #自定义消息
    def setupUi(self, parent):
        # 纵向布局
        self.parent = parent
        self.parent.setWindowTitle("迭代曲线及最优解")
        self.__init_ui_layout()

    def __init_ui_layout(self):
        layout = QtWidgets.QVBoxLayout(self.parent)
        layout.setContentsMargins(10, 10, 10, 10)  # 设置整体边距
        layout.setSpacing(5)  # 设置组件之间的间距

        self._ui_form = self.init_form()
        self._ui_plot = self.init_plot()
        
        btnCancel = QtWidgets.QPushButton("关闭")
        btnCancel.clicked.connect(lambda:self.parent.close())
        btnCancel.setMinimumWidth(80)
        btnCancel.setObjectName("DlgToolBtn")


        btnLayout = QtWidgets.QHBoxLayout()
        btnLayout.addWidget(btnCancel) 
        btnLayout.setAlignment(QtCore.Qt.AlignCenter)

        btnLayoutWidget = QtWidgets.QWidget()
        btnLayoutWidget.setLayout(btnLayout)

        # 添加组件到布局
        layout.addWidget(self._ui_form)
        layout.addWidget(self._ui_plot, 1)  # 设置拉伸因子为1
        layout.addWidget(btnLayoutWidget)


    def _init(self, data:dict={}) -> None:
        self.__data = data
        # 初始化表格数据
        # self._init_plot_data()

    def init_form(self):
        return envs.UIForm.UiCustomForm(self.__get_ui_form_config(), parent=self.parent)
    
    def init_plot(self):
        """
        初始化优化结果表格
        """
        plot_widget = envs.UIPlot.CustomPlot(title="迭代曲线")
        # 绘制数据
        # 设置标题和标签
        # plot_widget.set_title("运行迭代曲线")
        plot_widget.set_labels("迭代次数", "目标距离值")
        
        # 设置坐标轴范围
        return plot_widget
    
    def _init_plot_data(self, data:list=[]):
        """
        初始化表格数据
        """
        # 清理之前的绘图内容
        self._ui_plot.clear()
        
        # data 是个二维组 以下为测试数据
        if isinstance(data, list) and len(data) == 2:   
            self._ui_plot.set_limits(x_min=min(data[0]), x_max=max(data[0]), y_min=min(data[1]), y_max=max(data[1]))
            self._ui_plot.plot(data[0], data[1], label="迭代曲线", color="blue")
        else:
            print("警告：数据格式不正确")

    def _init_best_solution(self, data:list=[]):
        """
        初始化最优解
        """
        if isinstance(data, list) and len(data) == 2:
            # 更新 bestSolution 文本框 显示最优解
            self._ui_form._get_widget("bestSolution")._set(str(data[1][-1]))

    def __get_ui_form_config(self) -> json:
        return {
            "size":[200,20],
            "items":[
                {
                    "type": "file",
                    "key":"csvFile",
                    "typeParams": {
                        "title": "迭代曲线及最优解",
                        "fileType": "CSV Files (*.csv)",
                        "onSelected": lambda file: self._on_select_file(file)
                    },
                    "styleParams":{
                        "margin": [0, 0, 0, 0],
                        "space": 10,
                        "labWidth": 100,
                        "minWidth": 200,
                    }
                },
                {
                    "type": "text",
                    "key":"bestSolution",
                    "typeParams": {
                        "title": "最优解",
                    },
                    "styleParams":{
                        "margin": [0, 0, 0, 0],
                        "space": 10,
                        "labWidth": 100,
                        "minWidth": 200,
                    }
                },
            ]
        }
    
    def _on_select_file(self, file:str):
        """
        处理CSV文件选择
        Args:
            file: CSV文件路径
        """
        try:
            # 读取CSV文件
            with open(file, 'r', encoding='utf-8') as f:
                reader = csv.reader(f)
                data = self.init_csv_data(reader)
                
                # 检查数据是否为空
                if not data:
                    print("警告：CSV文件为空")
                    return
                    
                # 更新表格数据
                self._init_plot_data(data) 
                self._init_best_solution(data) 
                
        except FileNotFoundError:
            print(f"错误：找不到文件 {file}")
        except UnicodeDecodeError:
            try:
                # 尝试使用其他编码
                with open(file, 'r', encoding='gbk') as f:
                    reader = csv.reader(f)
                    data = self.init_csv_data(reader)
                    if not data:
                        print("警告：CSV文件为空")
                        return
                    self._init_plot_data(data)
                    self._init_best_solution(data) 
            except Exception as e:
                print(f"错误：无法读取文件 {file}，错误信息：{str(e)}")
        except Exception as e:
            print(f"错误：读取文件时发生错误 {str(e)}")
            # 打印测试数据
            data = [
                [2,3,4,5,6,7,8,9,10], # x 
                [3,11,110,1100,11000,110000,1100000,11000000,110000000], # y
            ]
            self._init_plot_data(data)
    
    def init_csv_data(self, reader:csv.reader):
        """
        初始化CSV数据 注意csv是多列数据 但是显示plot时 仅需要第一列序号列作为x轴 第二列作为y轴  
        """
        data = list(reader)
        # 跳过标题行
        if len(data) > 1:
            data = data[1:]
        x = [int(row[0]) for row in data]
        y = [float(row[1]) for row in data]
        return [x, y]
